package com.xfcode.service.impl;

import com.xfcode.api.vo.CreateWikiVO;
import com.xfcode.api.vo.QueryWikiPageVO;
import com.xfcode.domain.Wiki;
import com.xfcode.mapper.WikiMapper;
import com.xfcode.service.EsService;
import com.xfcode.service.SearcherService;
import com.xfcode.service.WikiService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
public class WikiServiceImpl  extends ServiceImpl<WikiMapper, Wiki> implements WikiService {
    @Autowired
    private EsService esService;
    @Autowired
    private  WikiMapper wikiMapper;

    @Override
    @Transactional
    public void save(CreateWikiVO createWikiVO) {
        String indexId = esService.saveToEs(createWikiVO);
        Wiki wiki=new Wiki();
        BeanUtils.copyProperties(createWikiVO,wiki);
        wiki.setCreateTime(new Date());
        wiki.setIndexId(indexId);
        this.save(wiki);
    }

    @Override
    public Page<Wiki> getPage(QueryWikiPageVO pageDto) {
        LambdaQueryWrapper<Wiki> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(null != pageDto.getKeywords(),Wiki::getKeywords,pageDto.getKeywords())
                .like(null != pageDto.getContent(),Wiki::getContent,pageDto.getContent())
                .like(null != pageDto.getTitle(),Wiki::getTitle,pageDto.getTitle())
                .ge(null != pageDto.getBeginTime(),Wiki::getCreateTime,pageDto.getBeginTime())
                .le(null != pageDto.getEndTime(),Wiki::getCreateTime,pageDto.getEndTime());
        return  wikiMapper.selectPage(pageDto,queryWrapper);
    }

    @Override
    public void updateById(Long id, CreateWikiVO createWikiVO) {
        Wiki wiki = wikiMapper.selectById(id);
        BeanUtils.copyProperties(createWikiVO,wiki);
         wikiMapper.updateById(wiki);
        esService.updateById(wiki.getIndexId(),createWikiVO);
    }

    @Override
    public void deleteById(Long id) {
        Wiki wiki = wikiMapper.selectById(id);
        wikiMapper.deleteById(wiki);
        esService.deleteById(wiki.getIndexId());
    }
}
